package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.CityHouseBean;
import com.weixin.paleituo.bean.CityListBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.LocationCityEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPager;
import com.weixin.paleituo.view.LocationCityPopu;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class LocationMapActivity extends BaseActivity {

    @BindView(R.id.iv_back_activity_loaction)
    ImageView mIvBackActivityLoaction;
    @BindView(R.id.ll_back_home_activity_location_map)
    LinearLayout mLlBackHomeActivityLocationMap;
    @BindView(R.id.tv_city_activity_location_map)
    TextView mTvCityActivityLocationMap;
    @BindView(R.id.ll_arrow_city_activity_location_map)
    LinearLayout mLlArrowCityActivityLocationMap;
    @BindView(R.id.iv_message_activity_location_map)
    ImageView mIvMessageActivityLocationMap;
    @BindView(R.id.map_activity_location_map)
    MapView mMapActivityLocationMap;
    @BindView(R.id.tv_house_name_activity_location_map)
    TextView mTvHouseNameActivityLocationMap;
    @BindView(R.id.tv_house_location_activity_location_map)
    TextView mTvHouseLocationActivityLocationMap;
    @BindView(R.id.tv_check_house_details_activity_location_map)
    TextView mTvCheckHouseDetailsActivityLocationMap;
    @BindView(R.id.ll_house_details_activity_location)
    LinearLayout mLlHouseDetailsActivityLocation;
    @BindView(R.id.rl_head_root_activity_location_map)
    RelativeLayout mHeadRoot;
    @BindView(R.id.tv_home_activity_locationMap_activity)
    TextView mTvHomeActivityLocationMapActivity;
    private String mCity = "";
    private BaiduMap mMapView;
    private List<Overlay> overlays;
    List<CityHouseBean> mCityHouseBeanList = new ArrayList<>();
    private String housesId = "";
    private LoadingPager mLoadingPager;
    private List<String> mStringList = new ArrayList<>();
    private Map<String, String> mMap = new HashMap<>();
    private String mSelectCity;
    private LocationCityPopu mLocationCityPopu;
    private Dialog mLoadingDialog;
    private BitmapDescriptor normalHouse = BitmapDescriptorFactory
            .fromResource(R.mipmap.normo_house);


    private BitmapDescriptor selectHouse = BitmapDescriptorFactory
            .fromResource(R.mipmap.select_house);
    private boolean mBooleanIsHome;
    private LatLng mLatLng;

    @Override
    protected void initView() {
        mLoadingPager = new LoadingPager(this) {
            @Override
            protected void close() {
                finish();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(LocationMapActivity.this, R.layout.activity_location_map);
            }

            @Override
            protected void reLoading() {
                retry();

            }
        };

       // setContentView(R.layout.activity_location_map);
        setContentView(mLoadingPager);

    }

    private InfoWindow mInfoWindow;

    @Override
    protected void initData() {

        super.initData();
        EventBus.getDefault().register(this);
        mLlHouseDetailsActivityLocation.setVisibility(View.INVISIBLE);
        Intent intent = getIntent();
        mCity = intent.getStringExtra(Contans.INTENT_DATA) == null ? "成都市" : intent.getStringExtra(Contans.INTENT_DATA);
        mBooleanIsHome = intent.getBooleanExtra(Contans.INTENT_BOOLEAN, true);
        mLatLng = intent.getParcelableExtra(Contans.INTENT_EXTRA);

        if (mBooleanIsHome) {
            mTvCityActivityLocationMap.setText(mCity);

        } else {
            mIvMessageActivityLocationMap.setVisibility(View.INVISIBLE);
            mImageViewArrow.setVisibility(View.INVISIBLE);

            mTvCityActivityLocationMap.setVisibility(View.INVISIBLE);
            mTvHomeActivityLocationMapActivity.setVisibility(View.INVISIBLE);

        }
        mMapView = mMapActivityLocationMap.getMap();
        mMapActivityLocationMap.showZoomControls(false);

        retry();

        mMapView.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                LogUtils.i(TAG, "dianji" + marker.toString());
               /* Button button = new Button(getApplicationContext());
                button.setBackgroundResource(R.mipmap.popup);*/
               if (mBooleanIsHome){
                   for (int i = 0; i < overlays.size(); i++) {
                       Marker marker1 = (Marker) overlays.get(i);
                       if (marker == marker1) {
                           marker.setIcon(selectHouse);
                           mLlHouseDetailsActivityLocation.setVisibility(View.VISIBLE);
                           CityHouseBean cityHouseBean = mCityHouseBeanList.get(i);
                           if (cityHouseBean != null) {
                               housesId = cityHouseBean.getHousesId();
                               mTvHouseNameActivityLocationMap.setText(cityHouseBean.getHouses() + "");
                               mTvHouseLocationActivityLocationMap.setText("具体位置:"+cityHouseBean.getSummary());
                           }

                       /* button.setText(cityHouseBean.getHouses()+"");
                        button.setTextColor(Color.BLACK);
                        button.setWidth(300);
                        LatLng ll = marker.getPosition();
                        mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), ll, -47, null);
                        mMapView.showInfoWindow(mInfoWindow);*/
                       } else {
                           marker1.setIcon(normalHouse);
                       }
                   }
               }
                return true;
            }
        });
    }
    /**
     * 重试
     */
    private void retry() {
        Observable<StatusCode<List<CityHouseBean>>> statusCodeObservable = ApiUtils.getApi().getCity(BaseApplication.getToken())
                .flatMap(new Function<StatusCode<List<CityListBean>>, ObservableSource<StatusCode<List<CityHouseBean>>>>() {
                    @Override
                    public ObservableSource<StatusCode<List<CityHouseBean>>> apply(StatusCode<List<CityListBean>> listStatusCode) throws Exception {
                        LogUtils.i(TAG, "初始化 ：获取城市列表" + listStatusCode);
                        LogUtils.i(TAG, "定位城市 ：：" + BaseApplication.sLocationCity);
                        if (listStatusCode != null && listStatusCode.isFlag() && listStatusCode.getData() != null) {
                            List<CityListBean> data = listStatusCode.getData();
                            mStringList.clear();
                            mMap.clear();
                            for (CityListBean cityListBean : data) {
                                mStringList.add(cityListBean.getName());
                                mMap.put(cityListBean.getShortName(), cityListBean.getId() + "");
                            }
                            for (CityListBean cityListBean : data) {
                                if (cityListBean.getName().equals(BaseApplication.sLocationCity)) {
                                    //获取城市列表成功
                                    mSelectCity = cityListBean.getName();
                                    return ApiUtils.getApi().getCityHouseLocation(Contans.defaultToken, mCity);
                                }
                            }
                        }
                        return ApiUtils.getApi().getCityHouseLocation(Contans.defaultToken, mCity);
                    }
                });


        HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<List<CityHouseBean>>(this) {
            @Override
            protected void _onNext(StatusCode<List<CityHouseBean>> listStatusCode) {
                mLoadingPager.showPagerView(Contans.STATE_SUCCEED);

                List<CityHouseBean> cityHouseBeans = listStatusCode.getData();
                if (listStatusCode.isFlag() && cityHouseBeans != null && cityHouseBeans.size() > 0) {
                    mCityHouseBeanList.addAll(cityHouseBeans);

                    //创建OverlayOptions的集合
                    //构建Marker图标


                    List<OverlayOptions> options = new ArrayList<OverlayOptions>();

                    for (CityHouseBean cityHouseBean : cityHouseBeans) {
                        //latitudeE6\
                        MarkerOptions option1;
                        LatLng point1 = new LatLng(cityHouseBean.getLatitude(), cityHouseBean.getLongitude());

                        if (!mBooleanIsHome && mLatLng != null && mLatLng.latitude == cityHouseBean.getLatitude() && mLatLng.longitude == cityHouseBean.getLongitude()) {
                            option1 = new MarkerOptions()
                                    .position(point1)
                                    .icon(selectHouse).zIndex(9).draggable(true);
                           /* mLlHouseDetailsActivityLocation.setVisibility(View.VISIBLE);
                            mTvHouseNameActivityLocationMap.setText(cityHouseBean.getHouses() + "");
                            mTvHouseLocationActivityLocationMap.setText(cityHouseBean.getSummary());
                            housesId = cityHouseBean.getHousesId();*/
                            options.add(option1);
                        } else {
                            if (mBooleanIsHome) {
                                option1 = new MarkerOptions()
                                        .position(point1)
                                        .icon(normalHouse).zIndex(9).draggable(true);
                                options.add(option1);
                            }

                        }


                    }

                    LatLng point = new LatLng(cityHouseBeans.get(0).getLatitude(), cityHouseBeans.get(0).getLongitude());

                    overlays = mMapView.addOverlays(options);
                    mMapView.setMapStatus(MapStatusUpdateFactory.newLatLng(point));

                } else {

                    // 当前定位城市无楼盘，弹框提示
                    ToastUtils.makeText("当前城市没有在售的楼盘");
                    mMapView.setMapStatus(MapStatusUpdateFactory.newLatLng(mLatLng));
                }


            }

            @Override
            protected void _onError(String message) {
                mLoadingPager.showPagerView(Contans.STATE_ERROR);
                ToastUtils.makeText(message);


            }
        }, "", lifecycleSubject, false, true);


    }

    @OnClick(R.id.ll_back_home_activity_location_map)
    public void onMLlBackHomeActivityLocationMapClicked() {
        finish();
    }

    @BindView(R.id.iv_arrow_activity_location_map)
    ImageView mImageViewArrow;

    @OnClick(R.id.ll_arrow_city_activity_location_map)
    public void onMLlArrowCityActivityLocationMapClicked(View view) {
        //  mTvCityActivityLocationMap.setText(mSelectCity+"");
        mImageViewArrow.setImageResource(R.mipmap.choose_cityup);
        if (mLocationCityPopu == null) {
            mLocationCityPopu = new LocationCityPopu(this);
            mLocationCityPopu.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mImageViewArrow.setImageResource(R.mipmap.choose_city);

                }
            });
        }

        mLocationCityPopu.setList(mStringList);
        mLocationCityPopu.setChekStr(mSelectCity + "");


        mLocationCityPopu.showAsDropDown(mHeadRoot);


    }

    @OnClick(R.id.iv_message_activity_location_map)
    public void onMIvMessageActivityLocationMapClicked() {

        if (BaseApplication.isLoginSuccess) {

            MyMessageActivity.startActivity(this, BaseApplication.getUserId());

        } else {
            LoginActivity.startActivity(this, true);
        }
    }

    public static void startActivity(Context context, String city, boolean isHome, LatLng latLng) {
        Intent intent = new Intent(context, LocationMapActivity.class);
        intent.putExtra(Contans.INTENT_DATA, city);
        intent.putExtra(Contans.INTENT_BOOLEAN, isHome);
        intent.putExtra(Contans.INTENT_EXTRA, latLng);
        context.startActivity(intent);
    }

    @OnClick(R.id.tv_check_house_details_activity_location_map)
    public void onViewClicked() {
        if (!StringUtils.isEmpty(housesId)) {
            HouseDetailsActivity.startActivity(this, housesId);

        } else {


            ToastUtils.makeText("楼盘id为空");
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void locationCityEvent(LocationCityEvent locationCityEvent) {
        final String mcity = locationCityEvent.getMcity();
        mLlHouseDetailsActivityLocation.setVisibility(View.INVISIBLE);

        if (!StringUtils.isEmpty(mcity)) {

            mTvCityActivityLocationMap.setText(mcity);
            if (!mcity.equals(mSelectCity)) {
                //调借口
                Observable cityHouseLocationObservable = ApiUtils.getApi()
                        .getCityHouseLocation(Contans.defaultToken, mcity).compose(RxHelper.getObservaleTransformer())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (mLoadingDialog == null) {

                                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(LocationMapActivity.this, "");
                                }
                                mLoadingDialog.show();
                            }
                        }).subscribeOn(AndroidSchedulers.mainThread());

                HttpUtil.getInstance().toSubscribe(cityHouseLocationObservable, new ProgressSubscriber<List<CityHouseBean>>(this) {
                    @Override
                    protected void _onNext(StatusCode<List<CityHouseBean>> listStatusCode) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);

                        List<CityHouseBean> cityHouseBeans = listStatusCode.getData();
                        if (listStatusCode.isFlag() && cityHouseBeans != null && cityHouseBeans.size() > 0) {
                            mSelectCity = mcity;
                            mCityHouseBeanList.clear();
                            mMapView.clear();
                            mCityHouseBeanList.addAll(cityHouseBeans);

                            //创建OverlayOptions的集合
                            //构建Marker图标


                            List<OverlayOptions> options = new ArrayList<OverlayOptions>();

                            for (CityHouseBean cityHouseBean : cityHouseBeans) {
                                //latitudeE6
                                LatLng point1 = new LatLng(cityHouseBean.getLatitude(), cityHouseBean.getLongitude());

                                MarkerOptions option1 = new MarkerOptions()
                                        .position(point1)
                                        .icon(normalHouse).zIndex(9).draggable(true);
                                options.add(option1);


                            }

                            LatLng point = new LatLng(cityHouseBeans.get(0).getLatitude(), cityHouseBeans.get(0).getLongitude());

                            overlays = mMapView.addOverlays(options);
                            mMapView.setMapStatus(MapStatusUpdateFactory.newLatLng(point));

                        } else {
                            ToastUtils.makeText(listStatusCode.getDetailMsg() + "");
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);

                    }
                }, "", lifecycleSubject, false, true);

            }


        }

    }

    @Override
    protected void onPause() {
        // MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
        mMapActivityLocationMap.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mMapActivityLocationMap.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mMapActivityLocationMap.onDestroy();
        super.onDestroy();

        EventBus.getDefault().unregister(this);
        normalHouse.recycle();
        selectHouse.recycle();

    }
    @OnClick(R.id.iv_delete_activity_location_map)
    public void closeShow(){

                for(Overlay overlay:overlays){
                    ((Marker)overlay).setIcon(normalHouse);


                }





        mLlHouseDetailsActivityLocation.setVisibility(View.INVISIBLE);
    }


}
